import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/my/my_page_logic.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/home/news_button_area.dart';
import 'package:sports_new/widgets/ads_label.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import 'package:visibility_detector/visibility_detector.dart';
import '../../server/api/pay_api.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/game_entry_widget.dart';

class MyPage extends StatefulWidget {
  const MyPage({super.key});

  @override
  State<MyPage> createState() => _MyPageState();
}

class _MyPageState extends State<MyPage> {
  final logic = Get.put(MyPageLogic());
  final visibleKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    final s = AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(statusBarBrightness: Brightness.light),
      child: GetBuilder<MyPageLogic>(
        builder: (logic) {
          return VisibilityDetector(
            key: const Key("my"),
            onVisibilityChanged: (VisibilityInfo info) async{
              if(!info.visibleBounds.isEmpty && User.isLogin){
                logic.coupons = await PayApi.myCoupons() ?? [];
              }
            },
            child: LoadingWidget<bool>(
              isLoading: false,
              data: false,
              reconnect: logic.getRefresh,
              child: () => Scaffold(
                backgroundColor: Colours.greyF2F3F7,
                extendBodyBehindAppBar: true,
                appBar: Styles.appBar(
                  backgroundColor: Colours.transparent,
                  showLeading: false
                ),
                body: Stack(
                  children: [
                    Obx(() => Container(
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: AssetImage(
                            Utils.getImgPath('my_header_bg.png')
                          ),
                          fit: BoxFit.cover
                        )
                      ),
                      height: logic.headerBgHeight.value,
                      )
                    ),
                    EasyRefresh.builder(
                      controller: logic.refreshC,
                      onRefresh: () async {
                        logic.onRefresh = true;
                        await User.fetchUserInfo();
                        if (User.isLogin) {
                          logic.coupons = await PayApi.myCoupons() ?? [];
                        }
                        update();
                        logic.onRefresh = false;
                      },
                      childBuilder: (context,physics) => ListView(
                        physics: physics,
                        children: [
                          header().paddingOnly(bottom: 22),
                          numSet().paddingOnly(bottom: 20),
                          if(ModeConfig.vipCenter)
                          vip(),
                          body()
                        ],
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
        }
      ),
    );
    return VisibilityDetector(
        key: visibleKey,
        child: s,
        onVisibilityChanged: (info) {
          if (!info.visibleBounds.isEmpty) {
            SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
                statusBarBrightness: Brightness.dark,
                statusBarIconBrightness: Brightness.dark));
            update();
          }
        });
  }

  Widget body() {
    return GetBuilder<MyPageLogic>(
      builder: (logic) {
        return Container(
          decoration: BoxDecoration(
            color: Colours.greyF2F3F7,
            borderRadius: const BorderRadius.vertical(top: Radius.circular(10)),
            boxShadow: [
              if(ModeConfig.vipCenter)
                BoxShadow(
                  offset: const Offset(0, -10),
                  blurRadius: 5,
                  spreadRadius: -5,
                  color: Colours.black.withOpacity(0.4)
                )
              ]
          ),
          child: Column(
            children: [
              userNeed(),
              if(logic.activeMenu.hasValue && ModeConfig.buttonArea)
              Block(
                cardStyle: const CardStyle(
                  margin: EdgeInsets.fromLTRB(8,8,8,0)
                ),
                child: NewsButtonArea(
                  menus: logic.activeMenu ?? [],
                  imageSize: 40,
                  tapType: 'my_portal',
                )
              ),
              if (Get.find<ResourceService>().webgames != null && ModeConfig.gameEntry)
                Block(
                  cardStyle: const CardStyle(
                    margin: EdgeInsets.fromLTRB(8, 8, 8, 0)
                  ),
                  child: GameEntryWidget(
                    lbts: Get.find<ResourceService>().webgames!,
                    scroll: !logic.onRefresh
                  )
                ),
              moreSet(),
              const AdsLabel(
                adsTag: "my",
                tapType: 'my_advertising',
                margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
              ),
              Container(height: 50),
            ],
          ),
        );
      }
    );
  }

  Widget avatar() => Stack(
    alignment: AlignmentDirectional.center,
    children: [
      QkdImage(
        imageUrl: User.info?.avatar ?? "",
        fit: BoxFit.cover,
        shape: BoxShape.circle,
        width: 60,
        height: 60,
        placeholder: Container(),
        errorWidget: Image.asset(Utils.getImgPath("my_person.png")),
      ),
      if(User.info?.isVip == 1)
      Image.asset(Utils.getImgPath("vip_frame.png"),width: 72),
    ],
  );

  Widget loginBtn() => Container(
        padding: const EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                QkdText(
                  User.isLogin? (User.info?.name ?? '') : "登录/注册",
                  color: User.info?.isVip == 1?
                  const Color(0xFF733305):Colours.text,
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
                if(User.info?.isVip == 1)
                Image.asset(
                  Utils.getImgPath("user_vip_label.png"),width: 68
                ).paddingOnly(left: 8)
              ],
            ),
            if(User.info?.isVip == 1)
            QkdText(
              "到期时间：${DateTime.tryParse(User.info?.vipEndTime ?? "")?.formatedString("yyyy年MM月dd日")}",
              fontSize: 12,color: Colours.grey99
            ).paddingOnly(top: 2)
          ],
        )
      );

  Widget header() => Stack(
    children: [
      Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(
            alignment: Alignment.centerLeft,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Row(
              children: [
                Row(children: [avatar(), loginBtn()]).tap(logic.tapHeaderName),
                const Spacer(),
                GestureDetector(
                    onTap: logic.tapTask,
                    child: Image.asset(Utils.getImgPath("my_task.png"),
                        width: 56),
                  )
              ],
            ),
          ),
        ],
      ),
    ],
  );

  Widget numSet(){
    return Row(
      children: <Widget>[
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              QkdText(
                User.info?.gold == null
                    ? '0.00'
                    : User.info!.gold!.toStringAsFixed(2),
                fontSize: 18,
                fontFamily: 'Din',
              ),
              const SizedBox(height: 2),
              QkdText(
                '我的球币'.changeUnit,
                color: Colours.grey999898,
              )
            ],
          ).tap(() => logic.tapRecharge(coin: true)),
        ),
        Expanded(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              QkdText("${logic.coupons?.length ?? 0}",
                  fontSize: 18,
                  fontFamily: 'Din'
              ),
              const SizedBox(height: 2),
              QkdText(
                '优惠券'.changeUnit,
                color: Colours.grey999898,
                fontSize: 14,
              )
            ],
          ).tap(logic.tapCoupons),
        ),
        Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Image.asset(width: 24,Utils.getImgPath("recharge_icon.png")),
                const SizedBox(height: 6),
                QkdButton(
                  width: 56,height: 24,
                  onPressed: logic.tapRecharge,
                  backgroundColor: Colours.main,
                  foregroundColor: Colours.white,
                  strutStyle: Styles.centerStyle(fontSize: 14),
                  textStyle: const TextStyle(fontSize: 12),
                  text: "充值",
                )
              ],
            )
        )
      ].insertEvery(Container(height: 24,width: 1,color: Colours.greyDD)),
    );
  }

  Widget vip() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 12),
      padding: const EdgeInsets.symmetric(horizontal: 16),
      alignment: Alignment.topCenter,
      height: 56,
      decoration: BoxDecoration(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(8)),
          image: DecorationImage(
              image: AssetImage(Utils.getImgPath('chongzhi_bg.png')),
              fit: BoxFit.cover)),
      child: Row(
          children: [
        Image.asset(width: 24,Utils.getImgPath('vip_icon.png')),
        Container(width: 8),
        const QkdText("VIP会员",
          needCenter: true,
          fontSize: 16,
          fontWeight: FontWeight.w500,
          color: Colours.goldFFCFA1
        ),
        const Spacer(),
        Container(
          width: 91,
          height: 32,
          alignment: Alignment.center,
          decoration: BoxDecoration(
              gradient: const LinearGradient(
                  stops: [0, 1],
                  colors: [Colours.goldFFE0B3, Colours.goldFFCA9C]),
              borderRadius: BorderRadius.circular(16)),
          child: QkdText(
            '立即${User.info?.isVip == 1?"续费":"开通"}',
            needCenter: true,
            fontWeight: FontWeight.w500,
          )
        )
      ]),
    ).tap(logic.tapVip);
  }
  
  Widget userNeed(){
    return Block(
      cardStyle: const CardStyle(
          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
          padding: EdgeInsets.symmetric(horizontal: 8)
      ),
      child: SizedBox(
        height: 86,
        child: Row(
          children: [
            Expanded(child: item("my_bill.png", "我的订单").tap(logic.tapPurchase)),
            Expanded(child: item("my_focus.png", "我的关注").tap(logic.tapMyFocus)),
            Expanded(child: item("my_collect.png", "我的收藏").tap(logic.tapMyCollection)),
          ],
        ),
      ),
    );
  }

  Widget moreSet(){
    return Block(
      cardStyle: const CardStyle(
          margin: EdgeInsets.fromLTRB(8, 8, 8, 0),
          padding: EdgeInsets.symmetric(vertical: 0)
      ),
      child: GridView.count(
        shrinkWrap: true,
        crossAxisCount: 4,
        physics: const NeverScrollableScrollPhysics(),
        children: [
          // item("my_share.png", "邀请得球币",
          //   alert: !SpUtils.shareClick,
          //   alertImage: Utils.getImgPath("share_gift_icon.png"),
          //   position: const Offset(-8, -15)
          // ).tap(logic.tapShare),
          item("my_contact.png", "联系客服").tap(logic.tapContact),
          item("my_question.png", "问题反馈").tap(logic.tapQuestion),
          item("my_setting.png", "更多设置",alert: logic.hasNewVersion).tap(logic.tapSettings),
          if(User.info?.isBindExpert??false)
            item("expert_live.png", "专家直播").tap(logic.tapLive)
          else
            item("my_expert_apply.png", "专家入驻").tap(logic.tapExpert),
        ],
      )
    );
  }

  Widget item(String image, String text,{bool alert = false,String? alertImage,Offset? position,double? size}) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Column(mainAxisSize: MainAxisSize.min, children: [
          Image.asset(Utils.getImgPath(image), width: size??24, height: size??24),
          const SizedBox(height: 6),
          QkdText(text,fontSize: 12),
        ]),
        if(alert)
        Positioned(
          top: position?.dx ?? 0,
          right: position?.dy ?? 0,
          child: alertImage != null?Image.asset(alertImage,height: 15):Container(
            width: 6,height: 6,
            decoration: const BoxDecoration(
              shape: BoxShape.circle,color: Colours.main
            )
          ),
        )
      ],
    ).center;
  }

  Widget billItem(String type) {
    return GestureDetector(
      onTap: () {
        Utils.onEvent(type == "bill"?"wdyg":"yhq");
        User.needLogin(
        () => Get.toNamed(type == "bill" ? Routes.myPurchase : Routes.myCoupons),
        fail: Get.back);
      },
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Image.asset(Utils.getImgPath("my_${type}_bg.png")),
          Positioned(
              left: 0,
              right: 0,
              child: Row(
                children: [
                  Image.asset(Utils.getImgPath("my_$type.png"), width: 28),
                  Container(width: 4),
                  QkdText(type == "bill" ? "我的订单" : "优惠券", fontSize: 16),
                  const Spacer(),
                  if (type == "coupon" && logic.coupons?.hasValue == true)
                  QkdText("${logic.coupons?.length ?? 0}张",
                    fontSize: 12, color: Colours.redE32F2F
                  ),
                  Image.asset(Utils.getImgPath("arrow_right_48.png"),
                    color: Colours.redE32F2F,
                    height: 16
                  )
                ],
              ).paddingSymmetric(horizontal: 12))
        ],
      ),
    );
  }
}
